package com.github.postsanf.yinian.activity;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.adapter.ImagelocalEditAdapter;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.SelectedImg;
import com.github.postsanf.yinian.service.UpLoadService;
import com.github.postsanf.yinian.utils.Bimp;
import com.github.postsanf.yinian.utils.DisplayUtils;
import com.github.postsanf.yinian.utils.SizeFormat;
import com.github.postsanf.yinian.utils.StringUtils;
import com.github.postsanf.yinian.utils.SystemUtils;
import com.github.postsanf.yinian.utils.TimeUtils;
import com.github.postsanf.yinian.utils.UIHelper;
import com.github.postsanf.yinian.utils.WrapContentLinearLayoutManager;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

public class ImageLocalEditActivity extends BaseActivity implements View.OnClickListener, PoiSearch.OnPoiSearchListener {
    private RecyclerView hrecyclerView;
    private ImagelocalEditAdapter editAdapter;
    private LinearLayout location_recommend;
    private LinearLayout imagelocaledit_location_addtx;
    private LinearLayout imagelocaledit_location_et;
    private LinearLayout location_edit;
    private LinearLayout location_show;
    private TextView imagelocaledit_location_show;
    private RelativeLayout imagelocaledit_recommendlocation;
    public AMapLocationClient mLocationClient = null;
    public AMapLocationClientOption mLocationOption = null;
    private PoiSearch.Query query;
    private PoiResult poiResult;
    private List<String> historyEplaces = new ArrayList<>();
    private TextView imagelocaledit_mic_tx;
    private ImageView iv_imagelocaledit_mic;
    private ImageView iv_imagelocaledit_mic_close;
    private EditText et_imagelocaledit;
    private ImageView iv_back;
    private TextView imagelocal_send;
    private TextView imagelocal_ed_sure;
    private ImageButton imagelocal_edit_cover;
    private RelativeLayout imagelocaledit_aite;
    private RelativeLayout imagelocaledit_aite_show;
    private LinearLayout aite_sel_hor;
    private ProgressDialog mProgressDialog;
    private ConnectivityManager mConnectivityManager;
    private String fsize;
    SharedPreferences.Editor editor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        registerBoradcastReceiver();
        setContentView(R.layout.yn_imagelocal_edit);
        mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        editor = getSharedPreferences(ACTIONs.mynetwork, 0).edit();
        mTempDir = new File(Environment.getExternalStorageDirectory(), "yinian/temp");
        if (!(mTempDir.mkdir() || mTempDir.isDirectory())) {
            mTempDir.mkdirs();
        }
        initHistoryEplaces();
        initView();
        initLocation();
    }

    private void initView() {
        iv_back = (ImageView) findViewById(R.id.iv_back);
        findViewById(R.id.rl_pop_top).setOnClickListener(this);
        findViewById(R.id.word_kit).setOnClickListener(this);
        imagelocal_send = (TextView) findViewById(R.id.imagelocal_send);
        imagelocal_ed_sure = (TextView) findViewById(R.id.imagelocal_ed_sure);
        iv_back.setOnClickListener(this);
        imagelocal_send.setOnClickListener(this);
        imagelocal_ed_sure.setOnClickListener(this);
        et_imagelocaledit = (EditText) findViewById(R.id.et_imagelocaledit);
        et_imagelocaledit.clearFocus();
        et_imagelocaledit.setCursorVisible(false);
        imagelocal_edit_cover = (ImageButton) findViewById(R.id.imagelocal_edit_cover);
        imagelocal_edit_cover.setOnClickListener(this);
        hrecyclerView = (RecyclerView) findViewById(R.id.rv_imagelocaledit_horizontal);
        WrapContentLinearLayoutManager horLayoutManager = new WrapContentLinearLayoutManager(this);
        horLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        hrecyclerView.setLayoutManager(horLayoutManager);
        editAdapter = new ImagelocalEditAdapter(this);
        hrecyclerView.setHasFixedSize(true);
        if (SelectedImg.mSelectedImage.size() > 0) {
            hrecyclerView.setAdapter(editAdapter);
        }
        location_edit = (LinearLayout) findViewById(R.id.location_edit);
        location_show = (LinearLayout) findViewById(R.id.location_show);
        imagelocaledit_location_show = (TextView) findViewById(R.id.imagelocaledit_location_show);
        location_show.setOnClickListener(this);
        imagelocaledit_recommendlocation = (RelativeLayout) findViewById(R.id.imagelocaledit_recommendlocation);
        location_recommend = (LinearLayout) findViewById(R.id.location_recommend);
        imagelocaledit_location_addtx = (LinearLayout) findViewById(R.id.imagelocaledit_location_addtx);
        imagelocaledit_location_et = (LinearLayout) findViewById(R.id.imagelocaledit_location_et);
        imagelocaledit_location_addtx.setOnClickListener(this);
        findViewById(R.id.imagelocaledit_location_close).setOnClickListener(this);
        findViewById(R.id.imagelocaledit_mic).setOnClickListener(this);
        iv_imagelocaledit_mic = (ImageView) findViewById(R.id.iv_imagelocaledit_mic);
        iv_imagelocaledit_mic_close = (ImageView) findViewById(R.id.iv_imagelocaledit_mic_close);
        iv_imagelocaledit_mic_close.setOnClickListener(this);
        imagelocaledit_mic_tx = (TextView) findViewById(R.id.imagelocaledit_mic_tx);
        imagelocaledit_aite = (RelativeLayout) findViewById(R.id.imagelocaledit_aite);
        imagelocaledit_aite_show = (RelativeLayout) findViewById(R.id.imagelocaledit_aite_show);
        aite_sel_hor = (LinearLayout) findViewById(R.id.aite_sel_hor);
        imagelocaledit_aite.setOnClickListener(this);
        aite_sel_hor.setOnClickListener(this);
        imagelocaledit_aite_show.setOnClickListener(this);
        sendBroadcast(new Intent("updateeditphone"));
        if (!StringUtils.isEmpty(MainActivity.locationTx)) {
            location_edit.setVisibility(View.GONE);
            imagelocaledit_location_show.setText(MainActivity.locationTx);
            location_show.setVisibility(View.VISIBLE);
        }
        sendBroadcast(new Intent(ACTIONs.actionMIcText));
    }

    private void initHistoryEplaces() {
        String urlsto = getString(R.string.BASE_URL) + "GetUserRecentlyUploadAddress";
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        StringRequest req = new StringRequest(urlsto)
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if (jsonObject.optString("msg").equals("success")) {
                                JSONArray dataArray = jsonObject.optJSONArray("data");
                                for (int i = 0; i < dataArray.length(); i++) {
                                    historyEplaces.add(dataArray.optJSONObject(i).optString("eplace"));
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
//                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    private View CreateTextView(String locationtx, int j) {
        View lView = LayoutInflater.from(this).inflate(R.layout.yn_imagelocal_edit_locationlayout, null);
        TextView ltv = (TextView) lView.findViewById(R.id.location_layout);
        ltv.setText(locationtx);
        ltv.setTag(locationtx);
        ltv.setOnClickListener(txListener);
        return lView;
    }

    View.OnClickListener txListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            String tx = (String) v.getTag();
            imagelocaledit_location_show.setText(tx);
            MainActivity.locationTx = tx;
            location_edit.setVisibility(View.GONE);
            location_show.setVisibility(View.VISIBLE);
            Animation translateAnimation = new TranslateAnimation(0, 0, UIHelper.dip2px(ImageLocalEditActivity.this, 15), 0);
            translateAnimation.setDuration(500);
            location_show.startAnimation(translateAnimation);
            translateAnimation.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                }

                @Override
                public void onAnimationEnd(Animation animation) {
//                    sendBroadcast(new Intent("editclose"));
                    imagelocaledit_location_addtx.setVisibility(View.GONE);
                    location_edit.setVisibility(View.GONE);
                    location_show.setVisibility(View.VISIBLE);
                }

                @Override
                public void onAnimationRepeat(Animation animation) {
                }
            });

        }
    };

    private void initLocation() {
        mLocationClient = new AMapLocationClient(getApplicationContext());
        mLocationClient.setLocationListener(mAMapLocationListener);
        mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
        mLocationOption.setOnceLocation(true);
        mLocationOption.setOnceLocationLatest(true);
        mLocationOption.setNeedAddress(true);
        mLocationOption.setMockEnable(false);
        mLocationOption.setHttpTimeOut(20000);
        mLocationOption.setLocationCacheEnable(false);
        mLocationClient.setLocationOption(mLocationOption);
        mLocationClient.startLocation();
    }


    @Override
    public void onPoiSearched(PoiResult result, int rCode) {
        if (rCode == 1000) {
            if (result != null && result.getQuery() != null) {
                if (result.getQuery().equals(query)) {
                    poiResult = result;
//                    final int resultPages = poiResult.getPageCount();
                    final List<PoiItem> poiItems = poiResult.getPois();
                    if (poiItems != null && poiItems.size() > 0) {
                        if (historyEplaces.size() > 0) {
                            for (int i = 0; i < 2; i++) {
                                location_recommend.addView(CreateTextView(poiItems.get(i).getTitle(), i));
                            }
                            for (int i = 0; i < historyEplaces.size(); i++) {
                                location_recommend.addView(CreateTextView(historyEplaces.get(i), i));
                            }
                        } else {
                            for (int i = 0; i < 6; i++) {
                                location_recommend.addView(CreateTextView(poiItems.get(i).getTitle(), i));
                            }
                        }
                        if (!StringUtils.isEmpty(MainActivity.locationTx)) {
                            imagelocaledit_recommendlocation.setVisibility(View.GONE);
                        } else {
                            imagelocaledit_recommendlocation.setVisibility(View.VISIBLE);
                        }
                    }
                }
            }
        } else {
//            Log.i("xjs", "rcode==>" + rCode);
        }
    }

    @Override
    public void onPoiItemSearched(PoiItem result, int code) {
    }

    PoiSearch poiSearch;
    String CityCode;
    AMapLocation pamapLocation;
    AMapLocationListener mAMapLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    pamapLocation = amapLocation;
                    CityCode = amapLocation.getCityCode();
                    query = new PoiSearch.Query("", "", CityCode);
                    query.setPageSize(4);
                    query.setPageNum(0);// 设置查第一页
                    poiSearch = new PoiSearch(ImageLocalEditActivity.this, query);
                    poiSearch.setBound(new PoiSearch.SearchBound(new LatLonPoint(amapLocation
                            .getLatitude(), amapLocation.getLongitude()), 1000));
                    poiSearch.setOnPoiSearchListener(ImageLocalEditActivity.this);
                    poiSearch.searchPOIAsyn();
                } else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                    Toast.makeText(ImageLocalEditActivity.this, "定位失败!", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(ImageLocalEditActivity.this, "定位失败!", Toast.LENGTH_SHORT).show();
            }
        }
    };

    private boolean locationEditDouble = true;
    private static final int DOUBLE_CLICK_TIME = 350;
    private boolean locationShowDouble = true;
    Handler locationEdithandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                startActivity(new Intent(ImageLocalEditActivity.this, ImageLocationEditActivity.class));
            }
        }
    };

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                et_imagelocaledit.setCursorVisible(true);
                imagelocal_edit_cover.setVisibility(View.VISIBLE);
                iv_back.setVisibility(View.GONE);
                imagelocal_send.setVisibility(View.GONE);
                imagelocal_ed_sure.setVisibility(View.VISIBLE);
                return false;
            } else {
                et_imagelocaledit.setCursorVisible(false);
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }


    public String getphoneNames() {
        if (AiteSelectActivity.phoneNames.size() > 0) {
            String phones = null;
            for (int j = 0; j < AiteSelectActivity.phoneNames.size(); j++) {
                String strings = AiteSelectActivity.phoneNames.get(j);
                if (phones == null) {
                    phones = strings;
                } else {
                    phones = phones + "," + strings;
                }
            }
            return phones;
        } else {
            return "";
        }
    }

    private ProgressDialog pd;
    private File mTempDir;

    Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 1) {
                if (pd != null)
                    pd.dismiss();
                if (mConnectivityManager.getActiveNetworkInfo() != null && mConnectivityManager.getActiveNetworkInfo().isAvailable()) {
                    if (mConnectivityManager.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI) {
                        //WiFi网络
                        doUpImg(false);
                    } else if (mConnectivityManager.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_MOBILE) {
                        //3g网络
                        int netfrist = getSharedPreferences(ACTIONs.mynetwork, 0).getInt(ACTIONs.networkFrist, 0);
                        String nettype = getSharedPreferences(ACTIONs.mynetwork, 0).getString(ACTIONs.networkType, "");
                        if (!nettype.equals("") && nettype.equals(ACTIONs.network3GWIFI)) {
                            doUpImg(false);
                        } else {
                            if (netfrist == 0) {
                                FristNetWork(fsize);
                                editor.putInt(ACTIONs.networkFrist, 1);
                                editor.commit();
                            } else {
                                SecondNetWork(fsize);
                            }
                        }
                    }
                } else {
                    if (pd != null)
                        pd.dismiss();
                }
            }
        }
    };

    public void FristNetWork(String fsize) {
        final AlertDialog dlg = new AlertDialog.Builder(this).create();
        dlg.show();
        Window window = dlg.getWindow();
        window.setContentView(R.layout.publish_network_dialog);
        TextView tt = (TextView) window.findViewById(R.id.pp_title);
        tt.setText("您现在处于移动网络环境下，将消耗" + fsize + "流量，是否使用流量继续上传?");
        final TextView ok = (TextView) window.findViewById(R.id.btn_ep_ok);
        ok.setText("不允许");
        ok.setBackgroundColor(getResources().getColor(R.color.white));
        ok.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                doUpImg(true);
                dlg.cancel();
            }
        });
        final TextView cancel = (TextView) window
                .findViewById(R.id.btn_ep_cancel);
        cancel.setText("确定");
        cancel.setBackgroundColor(getResources().getColor(R.color.white));
        cancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                editor.putString(ACTIONs.networkType, ACTIONs.network3GWIFI);
                editor.commit();
                doUpImg(false);
                dlg.cancel();
            }
        });
    }

    public void SecondNetWork(String fsize) {
        final AlertDialog dlg = new AlertDialog.Builder(this).create();
        dlg.show();
        Window window = dlg.getWindow();
        window.setContentView(R.layout.publish_network_dialog);
        TextView tt = (TextView) window.findViewById(R.id.pp_title);
        tt.setText(">_< 您关闭了使用流量上传开关，你在使用3g/4g网络环境下，这会消耗您" + fsize + "流量，确定继续上传吗？");
        final TextView ok = (TextView) window.findViewById(R.id.btn_ep_ok);
        ok.setText("取消");
        ok.setBackgroundColor(getResources().getColor(R.color.white));
        ok.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                dlg.cancel();
            }
        });
        final TextView cancel = (TextView) window
                .findViewById(R.id.btn_ep_cancel);
        cancel.setText("仅一次");
        cancel.setBackgroundColor(getResources().getColor(R.color.white));
        cancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                doUpImg(false);
                dlg.cancel();
            }
        });
    }

    private String contentstr;
    private long upstorge;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.word_kit:
                startActivity(new Intent(ImageLocalEditActivity.this, TextEditKitActivity.class));
                break;
            case R.id.imagelocal_send:
                contentstr = et_imagelocaledit.getText().toString();
                long totalSize = 0;
                for (int i = 0; i < SelectedImg.mSelectedImage.size(); i++) {
                    String address = SelectedImg.mSelectedImage.get(i);
                    if (!address.startsWith("http")) {
                        File uploadImg = new File(address);
                        long imgSize = uploadImg.length();
                        totalSize += imgSize;
                    }
                }
                upstorge = totalSize;
                fsize = SizeFormat.formatSize(totalSize);
                if (!ImageLocalSelectActivity.IsSmall) {
                    pd = ProgressDialog.show(ImageLocalEditActivity.this, "", "发布中...", false,
                            false);
                    mHandler.sendEmptyMessage(1);
                } else {
                    pd = ProgressDialog.show(ImageLocalEditActivity.this, "", "压缩中...", false,
                            false);
                    new Thread() {
                        @Override
                        public void run() {
                            super.run();
                            for (int i = 0; i < SelectedImg.mSelectedImage.size(); i++) {
                                if (!SelectedImg.mSelectedImage.get(i).startsWith("http")) {
                                    String mubiaostr = Bimp.compressImage2(SelectedImg.mSelectedImage.get(i), mTempDir);
                                    SelectedImg.mSelectedImage.set(i, mubiaostr);
                                }
                            }
                            mHandler.sendEmptyMessage(1);
                        }
                    }.start();
                }
                break;
            case R.id.rl_pop_top:
            case R.id.imagelocal_edit_cover:
            case R.id.imagelocal_ed_sure:
                imagelocal_edit_cover.setVisibility(View.GONE);
                iv_back.setVisibility(View.VISIBLE);
                imagelocal_send.setVisibility(View.VISIBLE);
                imagelocal_ed_sure.setVisibility(View.GONE);
                InputMethodManager imm = (InputMethodManager)
                        getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                break;
            case R.id.imagelocaledit_location_addtx:
                if (locationEditDouble == true) {
                    locationEditDouble = false;    //准备接受双击
                    Thread thread = new Thread() {
                        public void run() {
                            try {
                                sleep(DOUBLE_CLICK_TIME);  //线程睡眠
                                if (locationEditDouble == false) {
                                    locationEditDouble = true;
                                    locationEdithandler.sendEmptyMessage(1);
                                }
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    };
                    thread.start();
                } else {
                    locationEditDouble = true;
                    imagelocaledit_location_et.setVisibility(View.VISIBLE);
                    imagelocaledit_location_addtx.setVisibility(View.GONE);
                    Intent intent = new Intent(ImageLocalEditActivity.this, TimeCardwordActivity.class);
                    intent.putExtra("day_sign_content", "day_sign_content");
                    intent.putExtra("text_content", "");
                    startActivity(intent);
                }
                break;
            case R.id.location_show:
                if (locationShowDouble == true) {
                    locationShowDouble = false;
                    Thread thread = new Thread() {
                        public void run() {
                            try {
                                sleep(DOUBLE_CLICK_TIME);
                                if (locationShowDouble == false) {
                                    locationShowDouble = true;
                                    locationEdithandler.sendEmptyMessage(2);
                                }
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    };
                    thread.start();
                } else {
                    locationShowDouble = true;
                    Intent intent = new Intent(ImageLocalEditActivity.this, TimeCardwordActivity.class);
                    intent.putExtra("day_sign_content", "day_sign_content");
                    intent.putExtra("text_content", imagelocaledit_location_show.getText().toString());
                    startActivity(intent);
                }
                break;
            case R.id.imagelocaledit_location_close:
                MainActivity.locationTx = "";
                imagelocaledit_location_et.setVisibility(View.GONE);
                location_show.setVisibility(View.GONE);
                imagelocaledit_location_addtx.setVisibility(View.VISIBLE);
                imagelocaledit_recommendlocation.setVisibility(View.VISIBLE);
                Animation translateAnimation = new TranslateAnimation(0, 0, -UIHelper.dip2px(ImageLocalEditActivity.this, 12), 0);
                translateAnimation.setDuration(450);
                imagelocaledit_recommendlocation.startAnimation(translateAnimation);
                translateAnimation.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {
                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        imagelocaledit_location_addtx.setVisibility(View.VISIBLE);
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {
                    }
                });
                location_edit.setVisibility(View.VISIBLE);
                break;
            case R.id.imagelocaledit_mic:
                Intent micIntent = new Intent(ImageLocalEditActivity.this, MicAddActivity.class);
                startActivity(micIntent);
                break;
            case R.id.iv_imagelocaledit_mic_close:
                DelMicDialog();
                break;
            case R.id.imagelocaledit_aite:
                startActivity(new Intent(ImageLocalEditActivity.this, AiteSelectActivity.class));
                break;
            case R.id.aite_sel_hor:
            case R.id.imagelocaledit_aite_show:
                startActivity(new Intent(ImageLocalEditActivity.this, AiteSelectActivity.class));
                break;
            default:
                break;
        }
    }

    public void DelMicDialog() {
        android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(this);
        builder.setCancelable(false);
        final android.support.v7.app.AlertDialog dlg = builder.create();
        dlg.show();
        Window window = dlg.getWindow();
        window.setContentView(R.layout.pub_dialog);
        window.setBackgroundDrawableResource(R.color.transparent);
        WindowManager.LayoutParams layout = dlg.getWindow().getAttributes();
        layout.width = DisplayUtils.getScreenWidthPixels(this) - DisplayUtils.dp2px(this, 35 * 2);
        dlg.getWindow().setAttributes(layout);
        TextView tt = (TextView) window.findViewById(R.id.pp_title);
        tt.setText("提示");
        TextView content = (TextView) window.findViewById(R.id.pp_content);
        content.setText("是否删除已录入的声音");
        TextView cancel = (TextView) window
                .findViewById(R.id.btn_cancel);
        cancel.setText("取消");
        cancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                dlg.cancel();
            }
        });
        final TextView ok = (TextView) window.findViewById(R.id.btn_ok);
        ok.setText("删除");
        ok.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                MainActivity.micpath = "";
                MainActivity.mp3IsExist = false;
                MainActivity.micUrl = "";
                MainActivity.timer = 0;
                MicAddActivity.mMp3FileName = "";
                sendBroadcast(new Intent(ACTIONs.actionMIcText));
                dlg.cancel();
            }
        });
    }


    private void doUpImg(boolean isPause) {
        mProgressDialog = ProgressDialog.show(this, "", CommonConstants.TIP_LOAD_UP);
        Intent mIntent = new Intent(this, UpLoadService.class);
        mIntent.setAction(ACTIONs.actionPublishElement);
        mIntent.putExtra(ACTIONs.aUid, application.getCurID() + "");
        mIntent.putExtra(ACTIONs.aContent, contentstr);
        mIntent.putExtra(ACTIONs.upaudio, MainActivity.micUrl);
        mIntent.putExtra(ACTIONs.upplace, MainActivity.locationTx);
        mIntent.putExtra(ACTIONs.upplacepic, "");
        mIntent.putExtra(ACTIONs.upplaceLongitude, "");
        mIntent.putExtra(ACTIONs.upplaceLatitude, "");
        mIntent.putExtra(ACTIONs.uppeopleName, getphoneNames());
        mIntent.putExtra(ACTIONs.aisPause, isPause);
        mIntent.putExtra(ACTIONs.upmain, "0");
        mIntent.putExtra(ACTIONs.upstorage, SizeFormat.formatDouble(upstorge, SizeFormat.FZ_KB));
        mIntent.putExtra(ACTIONs.upsource, SystemUtils.getAppStoreName(ImageLocalEditActivity.this, "UMENG_CHANNEL"));
        if (ImageLocalSelectActivity.fromfrist) {
            mIntent.putExtra("isPush", "no");
            mIntent.putExtra(ACTIONs.aGid, ImageLocalSelectActivity.fromfristgid + "");
        } else {
            mIntent.putExtra(ACTIONs.aGid, application.getCurGid() + "");
        }
        startService(mIntent);
        startActivity(new Intent(this, UpLoadActivity.class).putExtra(ACTIONs.IstoSetWifi, isPause));
        Intent upIntent = new Intent(ACTIONs.actionCloseAlbum);
        upIntent.putExtra(ACTIONs.aIsClearSelect, 1);
        sendBroadcast(upIntent);
        mProgressDialog.dismiss();
        finish();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();

    }

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case "kitContent":
                    String ettext = et_imagelocaledit.getText().toString();
                    String text = intent.getStringExtra("text");
                    if (StringUtils.isEmpty(ettext)) {
                        et_imagelocaledit.setText(text);
                    } else {
                        et_imagelocaledit.setText(ettext + "\n" + text);
                    }
                    break;
                case "editclose":
                    location_show.setVisibility(View.VISIBLE);
                    location_edit.setVisibility(View.GONE);
                    break;
                case "updatelocationtx":
                    String tx = intent.getStringExtra("locationtx");
                    MainActivity.locationTx = tx;
                    imagelocaledit_location_show.setText(tx);
                    location_show.setVisibility(View.VISIBLE);
                    location_edit.setVisibility(View.GONE);
                    break;
                case ACTIONs.actionUpdateFromText:
                    String day_sign_content = intent.getStringExtra("day_sign_content");
                    if (day_sign_content != null) {
                        if (!day_sign_content.equals("")) {
                            MainActivity.locationTx = day_sign_content;
                            imagelocaledit_location_show.setText(day_sign_content);
                            MainActivity.locationTx = day_sign_content;
                            imagelocaledit_location_et.setVisibility(View.VISIBLE);
                            imagelocaledit_location_addtx.setVisibility(View.GONE);
                            location_show.setVisibility(View.VISIBLE);
                            location_edit.setVisibility(View.GONE);
                        } else {
                            imagelocaledit_location_et.setVisibility(View.GONE);
                            imagelocaledit_location_addtx.setVisibility(View.VISIBLE);
                            location_show.setVisibility(View.GONE);
                            location_edit.setVisibility(View.VISIBLE);
                        }
                    }
                    break;
                case ACTIONs.actionUpdateFromTextCancel:
                    String day_sign_content2 = intent.getStringExtra("day_sign_content");
                    if (!StringUtils.isEmpty(day_sign_content2)) {
                        MainActivity.locationTx = day_sign_content2;
                        imagelocaledit_location_show.setText(day_sign_content2);
                        imagelocaledit_location_et.setVisibility(View.VISIBLE);
                        imagelocaledit_location_addtx.setVisibility(View.GONE);
                        location_show.setVisibility(View.VISIBLE);
                        location_edit.setVisibility(View.GONE);
                    } else {
                        imagelocaledit_location_et.setVisibility(View.GONE);
                        imagelocaledit_location_addtx.setVisibility(View.VISIBLE);
                        location_show.setVisibility(View.GONE);
                        location_edit.setVisibility(View.VISIBLE);
                    }
                    break;
                case ACTIONs.actionMIcText:
                    if (!StringUtils.isEmpty(MainActivity.micUrl)) {
                        if (MainActivity.mp3IsExist) {
                            iv_imagelocaledit_mic.setImageResource(R.drawable.icon_edit_mic);
                            iv_imagelocaledit_mic_close.setVisibility(View.VISIBLE);
                            imagelocaledit_mic_tx.setText(TimeUtils.secToTime(MainActivity.timer));
                        } else {
                            imagelocaledit_mic_tx.setText("添加声音");
                            iv_imagelocaledit_mic_close.setVisibility(View.GONE);
                            iv_imagelocaledit_mic.setImageResource(R.drawable.icon_edit_mic_before);
                        }
                    } else {
                        imagelocaledit_mic_tx.setText("添加声音");
                        iv_imagelocaledit_mic_close.setVisibility(View.GONE);
                        iv_imagelocaledit_mic.setImageResource(R.drawable.icon_edit_mic_before);
                    }
                    break;
                case "updateeditphone":
                    if (AiteSelectActivity.phoneNames.size() > 0) {
                        imagelocaledit_aite.setVisibility(View.GONE);
                        aite_sel_hor.removeAllViews();
                        textViews.clear();
                        for (int i = 0; i < AiteSelectActivity.phoneNames.size(); i++) {
                            aite_sel_hor.addView(CreateAiteTextView(AiteSelectActivity.phoneNames.get(i)));
                        }
                        imagelocaledit_aite_show.setVisibility(View.VISIBLE);
                    } else {
                        imagelocaledit_aite.setVisibility(View.VISIBLE);
                        imagelocaledit_aite_show.setVisibility(View.GONE);
                    }
                    break;
            }
        }
    };


    private List<TextView> textViews = new ArrayList<>();

    private View CreateAiteTextView(String locationtx) {
        View lView = LayoutInflater.from(this).inflate(R.layout.yn_imagelocal_edit_locationlayout, null);
        TextView ltv = (TextView) lView.findViewById(R.id.location_layout);
        ltv.setText(locationtx);
        ltv.setTag(0);
        textViews.add(ltv);
        lView.setOnClickListener(AitetxListener);
        return lView;
    }

    View.OnClickListener AitetxListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            TextView ltv = (TextView) v.findViewById(R.id.location_layout);
            int tag = (int) ltv.getTag();
            if (tag != 1) {
                for (int i = 0; i < textViews.size(); i++) {
                    TextView othertx = textViews.get(i);
                    othertx.setTag(0);
                    othertx.setTextColor(Color.parseColor("#ffffff"));
                    othertx.setBackgroundResource(R.drawable.location_radio_btn);
                }
                ltv.setTextColor(Color.parseColor("#000000"));
                ltv.setBackgroundResource(R.drawable.location_radio_btn_yellow);
                ltv.setTag(1);
            } else {
                for (int i = 0; i < AiteSelectActivity.phoneNames.size(); i++) {
                    if (ltv.getText().toString().equals(AiteSelectActivity.phoneNames.get(i))) {
                        AiteSelectActivity.phoneNames.remove(i);
                    }
                }
                for (int i = 0; i < textViews.size(); i++) {
                    if (ltv.getText().toString().equals(textViews.get(i).getText().toString())) {
                        textViews.remove(i);
                        aite_sel_hor.removeViewAt(i);
                    }
                }
                if (AiteSelectActivity.phoneNames.size() == 0) {
                    imagelocaledit_aite.setVisibility(View.VISIBLE);
                    imagelocaledit_aite_show.setVisibility(View.GONE);
                }
            }
        }
    };

    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTIONs.actionUpdateFromText);
        myIntentFilter.addAction(ACTIONs.actionUpdateFromTextCancel);
        myIntentFilter.addAction(ACTIONs.actionMIcText);
        myIntentFilter.addAction("updatelocationtx");
        myIntentFilter.addAction("editclose");
        myIntentFilter.addAction("updateeditphone");
        myIntentFilter.addAction("kitContent");
        this.registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.unregisterReceiver(mBroadcastReceiver);
    }

}
